<template>
  <div class="risk-detail-container">
    <!-- 头部信息栏 -->
    <el-card class="header-card">
      <div class="header-operation">
        <h1 class="page-title">
          <i class="fa fa-bar-chart text-primary mr-2"></i>
          资产风险详情 - {{ assetIp }}
        </h1>
        <div class="operation-buttons">
          <el-button
            type="default"
            :icon="Refresh"
            @click="handleRefresh"
            size="small"
          >
            刷新
          </el-button>
          <el-button type="default" @click="handleReScore" size="small">
            <i class="fa fa-star-o mr-1"></i> 重新评分
          </el-button>
          <el-button
            type="default"
            :icon="ArrowLeft"
            @click="handleBack"
            size="small"
          >
            返回
          </el-button>
        </div>
      </div>

      <!-- 基础信息卡片 -->
      <el-card class="basic-info-card">
        <template #header>
          <div class="card-header">
            <i class="fa fa-list-alt text-primary mr-2"></i>
            <span class="card-title">基础信息</span>
          </div>
        </template>
        <el-descriptions
          :column="4"
          border
          class="basic-info-descriptions"
          v-loading="loading"
        >
          <el-descriptions-item label="资产IP">
            <span class="monospace-text">{{ assetIp }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="所属部门">{{
            department
          }}</el-descriptions-item>
          <el-descriptions-item label="评分模板">{{
            scoreTemplate
          }}</el-descriptions-item>
          <el-descriptions-item label="最后评分时间">{{
            lastScoreTime
          }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 评分与风险等级 -->
      <div class="score-risk-container">
        <el-card class="score-card">
          <template #header>
            <div class="card-header">
              <i class="fa fa-tachometer text-primary mr-2"></i>
              <span class="card-title">总分</span>
            </div>
          </template>
          <div class="score-content" v-loading="loading">
            <div class="score-value">
              {{ totalScore.toFixed(2) }}<span class="score-max">/100</span>
            </div>
            <div class="score-history">(无历史对比)</div>
          </div>
        </el-card>

        <el-card class="risk-card">
          <template #header>
            <div class="card-header">
              <i class="fa fa-exclamation-triangle text-primary mr-2"></i>
              <span class="card-title">风险等级</span>
            </div>
          </template>
          <div class="risk-content">
            <div class="risk-level">
              <span class="risk-indicator" :class="riskLevelIndicator"></span>
              {{ riskLevelText }}
            </div>
            <div class="risk-description">{{ riskDescription }}</div>
            <div class="risk-actions">
              <el-button
                type="text"
                size="small"
                @click="handleShowSuggestions"
              >
                查看整改建议
              </el-button>
              <el-button type="text" size="small" @click="showHistory = true">
                查看历史
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 维度评分详情 -->
    <el-card class="dimension-card">
      <template #header>
        <div class="card-header">
          <i class="fa fa-pie-chart text-primary mr-2"></i>
          <span class="card-title">维度评分详情</span>
        </div>
      </template>

      <!-- 评分维度标签页 -->
      <el-tabs
        v-model="activeDimension"
        class="dimension-tabs"
        @tab-change="handleDimensionChange"
        v-loading="loading"
      >
        <el-tab-pane
          v-for="dimension in dimensionList"
          :key="dimension.key"
          :label="`${dimension.name} (${dimension.score.toFixed(1)}分)`"
          :name="dimension.key"
        >
          <div class="dimension-content fade-in">
            <template
              v-if="
                currentDimensionDetail &&
                !currentDimensionDetail.details?.no_data
              "
            >
              <el-card class="dimension-detail-card">
                <div class="detail-header">
                  <h3 class="detail-title">{{ dimension.name }}</h3>
                  <div class="detail-score">
                    扣分:
                    {{ currentDimensionDetail.deduction?.toFixed(2) || 0 }} /
                    {{ dimension.maxScore.toFixed(1) }}
                    <el-tag
                      v-if="currentDimensionDetail.deduction > 0"
                      :type="
                        currentDimensionDetail.is_false_positive
                          ? 'success'
                          : 'warning'
                      "
                      size="small"
                      class="ml-2"
                    >
                      {{
                        currentDimensionDetail.is_false_positive
                          ? "已标记误报"
                          : "发现扣分"
                      }}
                    </el-tag>
                  </div>
                </div>

                <div class="detail-item">
                  <span class="detail-label">是否误报:</span>
                  <span class="detail-value">
                    <i
                      :class="
                        currentDimensionDetail.is_false_positive
                          ? 'fa fa-check text-success'
                          : 'fa fa-times text-danger'
                      "
                      class="mr-1"
                    ></i>
                    {{ currentDimensionDetail.is_false_positive ? "是" : "否" }}
                  </span>
                </div>

                <!-- 威胁情报维度详情 -->
                <template
                  v-if="
                    dimension.key === 'intelligence_match' &&
                    currentDimensionDetail.details
                  "
                >
                  <div class="detail-section">
                    <h4 class="section-title">详细信息:</h4>
                    <el-descriptions
                      :column="1"
                      class="detail-descriptions"
                      border
                    >
                      <el-descriptions-item label="情报ID">{{
                        currentDimensionDetail.details.intelligence_id || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="漏洞名称">{{
                        currentDimensionDetail.details.vul_name || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="威胁等级">
                        <el-tag
                          :type="(currentDimensionDetail.details.vul_level === 'Critical' ? 'danger' : currentDimensionDetail.details.vul_level === 'High' ? 'warning' : 'info') as any"
                        >
                          {{ currentDimensionDetail.details.vul_level || "-" }}
                        </el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="置信度">{{
                        currentDimensionDetail.details.confidence_level || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="匹配分数">{{
                        currentDimensionDetail.details.match_score?.toFixed(
                          3
                        ) || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="总匹配数">{{
                        currentDimensionDetail.details.total_matches || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="有POC">
                        {{
                          currentDimensionDetail.details.poc_available
                            ? "✅ 是"
                            : "❌ 否"
                        }}
                      </el-descriptions-item>
                      <el-descriptions-item label="有EXP">
                        {{
                          currentDimensionDetail.details.exploit_available
                            ? "✅ 是"
                            : "❌ 否"
                        }}
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>

                  <div
                    class="detail-section"
                    v-if="currentDimensionDetail.details.calculation_breakdown"
                  >
                    <h4 class="section-title">扣分计算:</h4>
                    <el-descriptions
                      :column="2"
                      class="calculation-descriptions"
                      border
                    >
                      <el-descriptions-item label="基础分">{{
                        currentDimensionDetail.details.calculation_breakdown
                          .base || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="等级权重">{{
                        currentDimensionDetail.details.calculation_breakdown
                          .level_weight || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="置信度权重">{{
                        currentDimensionDetail.details.calculation_breakdown
                          .conf_weight || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="综合系数">{{
                        currentDimensionDetail.details.calculation_breakdown.multiplier?.toFixed(
                          2
                        ) || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item
                        :span="2"
                        label="最终扣分"
                        class="final-deduct"
                      >
                        <span class="deduct-value">{{
                          currentDimensionDetail.details.calculation_breakdown.final?.toFixed(
                            2
                          ) || currentDimensionDetail.deduction?.toFixed(2)
                        }}</span>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </template>

                <!-- 合规状态维度详情 -->
                <template
                  v-else-if="
                    dimension.key === 'compliance_status' &&
                    currentDimensionDetail.details
                  "
                >
                  <div class="detail-section">
                    <h4 class="section-title">详细信息:</h4>
                    <el-descriptions
                      :column="2"
                      class="detail-descriptions"
                      border
                    >
                      <el-descriptions-item label="比对状态">
                        <el-tag
                          :type="(currentDimensionDetail.details.comparison_status === 'consistent' ? 'success' : 'warning') as any"
                        >
                          {{
                            currentDimensionDetail.details.comparison_status ===
                            "consistent"
                              ? "一致"
                              : currentDimensionDetail.details
                                  .comparison_status === "suspected"
                              ? "可疑"
                              : "未报备"
                          }}
                        </el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="问题端口">{{
                        currentDimensionDetail.details.port || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="总端口数">{{
                        currentDimensionDetail.details.total_ports || 0
                      }}</el-descriptions-item>
                      <el-descriptions-item label="描述">{{
                        currentDimensionDetail.details.description || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item :span="2" label="状态分布">
                        <div style="margin-top: 8px">
                          <el-tag size="small" style="margin-right: 8px">
                            一致:
                            {{
                              currentDimensionDetail.details.status_counts
                                ?.consistent || 0
                            }}
                          </el-tag>
                          <el-tag
                            type="warning"
                            size="small"
                            style="margin-right: 8px"
                          >
                            可疑:
                            {{
                              currentDimensionDetail.details.status_counts
                                ?.suspected || 0
                            }}
                          </el-tag>
                          <el-tag type="danger" size="small">
                            未报备:
                            {{
                              currentDimensionDetail.details.status_counts
                                ?.unreported || 0
                            }}
                          </el-tag>
                        </div>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </template>

                <!-- 漏洞风险维度详情 -->
                <template
                  v-else-if="
                    dimension.key === 'vulnerability_risk' &&
                    currentDimensionDetail.details &&
                    !currentDimensionDetail.details.no_data
                  "
                >
                  <div class="detail-section">
                    <h4 class="section-title">详细信息:</h4>
                    <el-descriptions
                      :column="2"
                      class="detail-descriptions"
                      border
                    >
                      <el-descriptions-item label="最高等级">
                        <el-tag
                          :type="(currentDimensionDetail.details.highest_level === 'critical' ? 'danger' : currentDimensionDetail.details.highest_level === 'high' ? 'warning' : 'info') as any"
                        >
                          {{
                            currentDimensionDetail.details.highest_level || "-"
                          }}
                        </el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="漏洞总数">{{
                        currentDimensionDetail.details.total_count || 0
                      }}</el-descriptions-item>
                      <el-descriptions-item label="基础扣分">{{
                        currentDimensionDetail.details.base_deduction?.toFixed(
                          2
                        ) || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="系数">{{
                        currentDimensionDetail.details.multiplier?.toFixed(2) ||
                        "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item
                        :span="2"
                        label="最终扣分"
                        class="final-deduct"
                      >
                        <span class="deduct-value">{{
                          currentDimensionDetail.details.final_deduction?.toFixed(
                            2
                          ) || currentDimensionDetail.deduction?.toFixed(2)
                        }}</span>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </template>

                <!-- 高危端口维度详情 -->
                <template
                  v-else-if="
                    dimension.key === 'high_risk_port' &&
                    currentDimensionDetail.details &&
                    !currentDimensionDetail.details.no_data
                  "
                >
                  <div class="detail-section">
                    <h4 class="section-title">详细信息:</h4>
                    <el-descriptions
                      :column="2"
                      class="detail-descriptions"
                      border
                    >
                      <el-descriptions-item label="最高风险等级">
                        <el-tag
                          :type="(currentDimensionDetail.details.highest_risk_level === 'high' ? 'danger' : 'warning') as any"
                        >
                          {{
                            currentDimensionDetail.details.highest_risk_level ||
                            "-"
                          }}
                        </el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="最高风险端口">{{
                        currentDimensionDetail.details.highest_risk_port || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="服务">{{
                        currentDimensionDetail.details.service || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="原因">{{
                        currentDimensionDetail.details.reason || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="总数量">{{
                        currentDimensionDetail.details.total_count || 0
                      }}</el-descriptions-item>
                    </el-descriptions>
                  </div>
                </template>

                <!-- 资产加权维度详情 -->
                <template
                  v-else-if="
                    dimension.key === 'domain_weight' &&
                    currentDimensionDetail.details
                  "
                >
                  <div class="detail-section">
                    <h4 class="section-title">详细信息:</h4>
                    <el-descriptions
                      :column="2"
                      class="detail-descriptions"
                      border
                    >
                      <el-descriptions-item label="重要性等级">{{
                        currentDimensionDetail.details.importance_level || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="IP段资产数">{{
                        currentDimensionDetail.details.asset_count || 0
                      }}</el-descriptions-item>
                      <el-descriptions-item label="加权系数">{{
                        currentDimensionDetail.details.multiplier?.toFixed(2) ||
                        "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item label="其他维度总扣分">{{
                        currentDimensionDetail.details.other_dimensions_deduction?.toFixed(
                          2
                        ) || "-"
                      }}</el-descriptions-item>
                      <el-descriptions-item
                        :span="2"
                        label="加权影响"
                        class="final-deduct"
                      >
                        <span class="deduct-value">{{
                          currentDimensionDetail.details.weighted_impact?.toFixed(
                            2
                          ) || 0
                        }}</span>
                      </el-descriptions-item>
                    </el-descriptions>
                    <el-alert
                      v-if="currentDimensionDetail.details.final_message"
                      :title="currentDimensionDetail.details.final_message"
                      type="info"
                      :closable="false"
                      style="margin-top: 10px"
                    />
                  </div>
                </template>

                <!-- 无数据提示 -->
                <template v-else-if="currentDimensionDetail.details?.no_data">
                  <el-alert
                    :title="
                      currentDimensionDetail.details.reason || '该维度暂无数据'
                    "
                    type="info"
                    :closable="false"
                    style="margin: 20px"
                  />
                </template>

                <div class="detail-actions">
                  <el-button
                    v-if="
                      !currentDimensionDetail.is_false_positive &&
                      currentDimensionDetail.deduction > 0
                    "
                    type="warning"
                    size="small"
                    @click="handleMarkFalsePositive"
                  >
                    标记为误报
                  </el-button>
                  <el-button
                    v-if="currentDimensionDetail.is_false_positive"
                    type="default"
                    size="small"
                    @click="handleUnmarkFalsePositive"
                  >
                    取消误报标记
                  </el-button>
                </div>
              </el-card>
            </template>

            <template v-else>
              <el-empty description="该维度暂无详细信息" :image-size="100" />
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 整改建议对话框 -->
    <el-dialog
      v-model="showSuggestions"
      title="整改建议"
      width="800px"
      destroy-on-close
      @opened="fetchRemediationAdvice"
    >
      <div v-loading="adviceLoading">
        <el-card v-if="remediationAdvice">
          <!-- 总览 -->
          <el-descriptions :column="4" border style="margin-bottom: 20px">
            <el-descriptions-item label="当前分数">
              <span style="font-size: 18px; font-weight: bold; color: #1890ff">
                {{ remediationAdvice.current_score?.toFixed(2) }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="预期分数">
              <span style="font-size: 18px; font-weight: bold; color: #52c41a">
                {{ remediationAdvice.expected_score?.toFixed(2) }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="预期提升">
              <span style="font-size: 18px; font-weight: bold; color: #faad14">
                +{{ remediationAdvice.expected_improvement?.toFixed(2) }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="待整改项">
              {{ remediationAdvice.total_advice_count || 0 }}
            </el-descriptions-item>
          </el-descriptions>

          <el-alert
            v-if="remediationAdvice.summary"
            :title="remediationAdvice.summary.message"
            :description="remediationAdvice.summary.recommendation"
            :type="
              remediationAdvice.total_advice_count === 0 ? 'success' : 'warning'
            "
            :closable="false"
            style="margin-bottom: 20px"
          />

          <!-- 建议列表 -->
          <el-empty
            v-if="
              !remediationAdvice.advice_list ||
              remediationAdvice.advice_list.length === 0
            "
            description="✅ 暂无需要整改的问题"
          />

          <el-collapse v-else v-model="activeAdviceCollapse">
            <el-collapse-item
              v-for="(advice, index) in remediationAdvice.advice_list"
              :key="index"
              :name="index"
            >
              <template #title>
                <div style="display: flex; align-items: center; width: 100%">
                  <span style="margin-right: 8px">{{
                    advice.icon || "⚠️"
                  }}</span>
                  <span style="flex: 1; font-weight: bold">{{
                    advice.title
                  }}</span>
                  <el-tag
                    :type="(advice.risk_level === 'critical' || advice.risk_level === 'high' ? 'danger' : 'warning') as any"
                    size="small"
                    style="margin-right: 8px"
                  >
                    {{ advice.risk_level }}
                  </el-tag>
                  <el-tag type="info" size="small" style="margin-right: 8px">
                    扣分: {{ advice.current_deduction?.toFixed(2) }}
                  </el-tag>
                  <el-tag type="success" size="small">
                    预期提升: +{{ advice.expected_improvement?.toFixed(2) }}
                  </el-tag>
                </div>
              </template>

              <div class="advice-content">
                <el-descriptions :column="2" border style="margin-bottom: 15px">
                  <el-descriptions-item label="维度">{{
                    advice.dimension_name
                  }}</el-descriptions-item>
                  <el-descriptions-item label="建议时限">{{
                    advice.timeframe
                  }}</el-descriptions-item>
                  <el-descriptions-item label="工作量">{{
                    advice.effort_desc
                  }}</el-descriptions-item>
                  <el-descriptions-item label="优先级">{{
                    advice.priority?.toFixed(1)
                  }}</el-descriptions-item>
                </el-descriptions>

                <div class="advice-section">
                  <h4>📝 问题描述</h4>
                  <p>{{ advice.description }}</p>
                  <p
                    v-if="advice.details?.message"
                    style="color: #409eff; font-weight: bold; margin-top: 8px"
                  >
                    {{ advice.details.message }}
                  </p>
                </div>

                <div class="advice-section">
                  <h4>🔧 整改步骤</h4>
                  <ol style="padding-left: 20px; line-height: 1.8">
                    <li v-for="(step, i) in advice.steps" :key="i">
                      {{ step }}
                    </li>
                  </ol>
                </div>

                <div
                  class="advice-section"
                  v-if="advice.resources && advice.resources.length > 0"
                >
                  <h4>📦 所需资源</h4>
                  <el-tag
                    v-for="resource in advice.resources"
                    :key="resource"
                    style="margin-right: 8px; margin-bottom: 8px"
                  >
                    {{ resource }}
                  </el-tag>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </div>
    </el-dialog>

    <!-- 历史记录对话框 -->
    <el-dialog
      v-model="showHistory"
      title="评分历史"
      width="1000px"
      destroy-on-close
    >
      <el-card style="margin-bottom: 20px">
        <el-radio-group
          v-model="historyDays"
          @change="
            () => {
              historyPagination.currentPage = 1;
              fetchHistoryList();
            }
          "
        >
          <el-radio-button :label="7">最近7天</el-radio-button>
          <el-radio-button :label="30">最近30天</el-radio-button>
          <el-radio-button :label="90">最近90天</el-radio-button>
        </el-radio-group>
      </el-card>

      <div
        ref="historyChartRef"
        style="height: 350px; margin-bottom: 20px"
      ></div>

      <DynamicTable
        :pagination="historyPagination"
        :columns="historyColumns"
        :data="historyList"
        :loading="historyLoading"
        @current-page-change="handleHistoryPageChange"
        @size-change="handleHistorySizeChange"
      >
        <template #toolbar-right>
          <el-button
            type="primary"
            :icon="Refresh"
            @click="fetchHistoryList"
            size="small"
          >
            刷新
          </el-button>
        </template>
      </DynamicTable>
    </el-dialog>

    <!-- 误报标记对话框 -->
    <el-dialog
      v-model="showFalsePositiveDialog"
      title="标记误报"
      width="600px"
      destroy-on-close
    >
      <el-form :model="falsePositiveForm" label-width="120px">
        <el-form-item label="资产IP">
          <el-input v-model="assetIp" disabled />
        </el-form-item>
        <el-form-item label="维度">
          <el-input
            :value="
              dimensionList.find((d) => d.key === activeDimension)?.name ||
              activeDimension
            "
            disabled
          />
        </el-form-item>
        <el-form-item label="当前扣分">
          <el-tag type="danger"
            >{{ currentDimensionDetail?.deduction?.toFixed(2) || 0 }} 分</el-tag
          >
        </el-form-item>
        <el-form-item label="误报原因" required>
          <el-input
            v-model="falsePositiveForm.false_positive_reason"
            type="textarea"
            :rows="4"
            placeholder="请详细说明为什么认为这是误报，例如：已人工确认该告警为误报，实际版本不受影响"
          />
        </el-form-item>
        <el-form-item label="支持证据" required>
          <el-input
            v-model="falsePositiveForm.evidence"
            type="textarea"
            :rows="3"
            placeholder="请提供支持证据，例如：版本信息、扫描截图、人工复测结果等"
          />
        </el-form-item>
        <el-form-item label="处理方式">
          <el-radio-group v-model="falsePositiveForm.handling_method">
            <el-radio label="exclude_from_score">从评分中排除（推荐）</el-radio>
            <el-radio label="mark_only">仅标记不影响评分</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标记人">
          <el-input
            v-model="falsePositiveForm.marked_by"
            placeholder="请输入您的用户名"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showFalsePositiveDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitFalsePositive"
          :loading="loading"
          >确认标记</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  computed,
  watch,
  nextTick,
  h,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import {
  ElMessage,
  ElMessageBox,
  ElTag,
  ElProgress,
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElCard,
  ElButton,
  ElTabs,
  ElTabPane,
  ElEmpty,
  ElAlert,
  ElCollapse,
  ElCollapseItem,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadioGroup,
  ElRadio,
  ElRadioButton,
} from "element-plus";
import { Refresh, ArrowLeft } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import {
  getAssetScoreDetail,
  getScoreHistory,
  getRemediationAdvice,
  markFalsePositive,
  unmarkFalsePositive,
  calculateAssetScore,
} from "../servers";

const route = useRoute();
const router = useRouter();

// 从路由获取资产IP
const assetIp = ref<string>(
  (route.query.ip as string) || (route.params.ip as string) || ""
);
const loading = ref(false);
const detailLoading = ref(false);

// 资产基础信息
const department = ref("未知部门");
const scoreTemplate = ref("standard_v1");
const lastScoreTime = ref("2025-11-03 16:02:40");
const assetDetail = ref<any>(null);

// 评分与风险信息
const totalScore = computed(() =>
  parseFloat(assetDetail.value?.total_score || 0)
);
const riskLevel = computed(() => assetDetail.value?.risk_level || "low");
const riskLevelText = computed(() => {
  const levelMap: Record<string, string> = {
    low: "Low Risk (低风险)",
    medium: "Medium Risk (中风险)",
    high: "High Risk (高风险)",
    critical: "Critical Risk (严重风险)",
    safe: "Safe (安全)",
  };
  return levelMap[riskLevel.value] || "Unknown Risk";
});
const riskLevelIndicator = computed(() => {
  const indicatorMap: Record<string, string> = {
    low: "bg-success",
    medium: "bg-warning",
    high: "bg-orange-500",
    critical: "bg-danger",
    safe: "bg-success",
  };
  return indicatorMap[riskLevel.value] || "bg-gray-400";
});
const riskDescription = computed(() => {
  const descriptions: Record<string, string> = {
    critical: "资产存在严重安全风险，请立即处理！",
    high: "资产存在较大安全风险，建议尽快修复",
    medium: "存在一定安全风险，建议及时整改",
    low: "资产安全状况良好，继续保持",
    safe: "资产安全状况优秀",
  };
  return descriptions[riskLevel.value] || "资产安全状况良好，继续保持";
});

// 维度代码映射
const dimensionNameMap: Record<string, string> = {
  compliance_status: "合规状态",
  vulnerability_risk: "漏洞风险",
  intelligence_match: "威胁情报",
  high_risk_port: "高危端口",
  local_remote_diff: "本地差异",
  domain_weight: "资产加权",
};

// 维度评分数据
const dimensionList = computed(() => {
  if (!assetDetail.value?.dimension_scores) return [];
  return Object.entries(assetDetail.value.dimension_scores).map(
    ([key, dim]: [string, any]) => ({
      key,
      name: dimensionNameMap[key] || key,
      score: dim.deduction || 0,
      maxScore: dim.max_score || 0,
      dimension: dim,
    })
  );
});

const activeDimension = ref("");
const currentDimensionDetail = computed(() => {
  if (!activeDimension.value || !assetDetail.value?.dimension_scores)
    return null;
  return assetDetail.value.dimension_scores[activeDimension.value];
});

// 对话框控制
const showSuggestions = ref(false);
const showHistory = ref(false);
const showFalsePositiveDialog = ref(false);
const falsePositiveForm = reactive({
  false_positive_reason: "",
  evidence: "",
  handling_method: "exclude_from_score" as
    | "exclude_from_score"
    | "adjust_score"
    | "mark_only",
  marked_by: "",
});

// 整改建议数据
const remediationAdvice = ref<any>(null);
const adviceLoading = ref(false);
const activeAdviceCollapse = ref<number[]>([0]);

// 历史趋势图
const historyChartRef = ref<HTMLDivElement>();
let historyChart: echarts.ECharts | null = null;
const historyDays = ref(30);

// 历史记录分页配置
const historyPagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 历史记录数据
const historyList = ref([]);
const historyLoading = ref(false);

// 历史记录表格列定义
const historyColumns = ref<TableColumn[]>([
  {
    label: "评分时间",
    prop: "calculated_at",
    width: 180,
    show: true,
  },
  {
    label: "总分",
    prop: "total_score",
    width: 100,
    show: true,
    render: (row) =>
      h(
        "span",
        { style: { fontWeight: "bold" } },
        parseFloat(row.total_score || 0).toFixed(2)
      ),
  },
  {
    label: "风险等级",
    prop: "risk_level",
    width: 120,
    show: true,
    render: (row) => {
      const levelMap: Record<
        string,
        { text: string; type: "success" | "warning" | "danger" | "info" | "" }
      > = {
        low: { text: "低风险", type: "success" },
        medium: { text: "中风险", type: "warning" },
        high: { text: "高风险", type: "danger" },
        critical: { text: "严重风险", type: "danger" },
        safe: { text: "安全", type: "success" },
      };
      const item = levelMap[row.risk_level] || {
        text: row.risk_level,
        type: "" as "",
      };
      return h(
        ElTag,
        { type: item.type || undefined, size: "small" },
        item.text
      );
    },
  },
  {
    label: "分数变化",
    prop: "score_change",
    width: 120,
    show: true,
    render: (row) => {
      const change = parseFloat(row.score_change || 0);
      const color = change > 0 ? "#52c41a" : change < 0 ? "#f5222d" : "#909399";
      const text = change > 0 ? `+${change.toFixed(2)}` : change.toFixed(2);
      return h("span", { style: { color, fontWeight: "bold" } }, text);
    },
  },
  {
    label: "变更原因",
    prop: "change_reason",
    minWidth: 200,
    show: true,
  },
]);

// 获取资产详情
const fetchAssetDetail = async () => {
  if (!assetIp.value) {
    ElMessage.error("资产IP不能为空");
    router.back();
    return;
  }

  loading.value = true;
  try {
    const { data } = await getAssetScoreDetail({
      asset_ip: assetIp.value,
      include_raw_data: true,
    });

    if (data) {
      assetDetail.value = data;
      department.value = data.department || "未知部门";
      scoreTemplate.value = data.template_code || "standard_v1";
      lastScoreTime.value = data.calculated_at || "";

      // 设置默认激活的维度（第一个有扣分的维度）
      const firstDimensionWithDeduction = dimensionList.value.find(
        (dim) => dim.score > 0
      );
      if (firstDimensionWithDeduction) {
        activeDimension.value = firstDimensionWithDeduction.key;
      } else if (dimensionList.value.length > 0) {
        activeDimension.value = dimensionList.value[0].key;
      }
    }
  } catch (e: any) {
    console.error("获取资产详情失败:", e);
    ElMessage.error(e?.message || "获取资产详情失败");
  } finally {
    loading.value = false;
  }
};

// 方法定义
const handleRefresh = async () => {
  await fetchAssetDetail();
  ElMessage.success("数据刷新成功");
};

const handleReScore = async () => {
  if (!assetIp.value) return;

  try {
    await ElMessageBox.confirm("确定要重新评分该资产吗？", "确认重新评分", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    loading.value = true;
    const { data } = await calculateAssetScore({
      asset_ip: assetIp.value,
    });

    if (data) {
      ElMessage.success(
        `重新评分完成！新评分: ${data.total_score?.toFixed(2) || "N/A"}`
      );
      await fetchAssetDetail();
    } else {
      ElMessage.error("重新评分失败");
    }
  } catch (e: any) {
    if (e !== "cancel") {
      console.error("重新评分失败:", e);
      ElMessage.error(e?.message || "重新评分失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleBack = () => {
  router.back();
};

const handleDimensionChange = (key: string) => {
  activeDimension.value = key;
};

const fetchHistoryList = async () => {
  if (!assetIp.value) return;

  historyLoading.value = true;
  try {
    const { data } = await getScoreHistory({
      asset_ip: assetIp.value,
      days: historyDays.value,
      page: historyPagination.currentPage,
      page_size: historyPagination.pageSize,
    });

    if (data) {
      historyList.value = data.history_records || [];
      historyPagination.total = data.total || 0;

      // 绘制趋势图
      if (data.trend_data && data.trend_data.length > 0) {
        await nextTick();
        renderHistoryChart(data.trend_data);
      }
    }
  } catch (error: any) {
    console.error("获取历史记录失败:", error);
    ElMessage.error(error?.message || "获取历史记录失败");
  } finally {
    historyLoading.value = false;
  }
};

// 绘制历史趋势图
const renderHistoryChart = (trendData: any[]) => {
  if (!historyChartRef.value) return;

  if (historyChart) {
    historyChart.dispose();
  }
  historyChart = echarts.init(historyChartRef.value);

  const dates = trendData.map((item) => item.date);
  const scores = trendData.map((item) => parseFloat(item.total_score || 0));

  const option = {
    title: { text: `评分趋势（最近${historyDays.value}天）`, left: "center" },
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        const item = params[0];
        const record = trendData[item.dataIndex];
        return `${item.axisValue}<br/>分数: ${item.value}<br/>风险等级: ${record.risk_level}`;
      },
    },
    xAxis: {
      type: "category",
      data: dates,
      axisLabel: { rotate: 45 },
    },
    yAxis: {
      type: "value",
      min: 0,
      max: 100,
      name: "分数",
    },
    series: [
      {
        name: "评分",
        type: "line",
        data: scores,
        smooth: true,
        lineStyle: { width: 3, color: "#409EFF" },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
              { offset: 1, color: "rgba(64, 158, 255, 0.05)" },
            ],
          },
        },
        markLine: {
          silent: true,
          lineStyle: { type: "dashed" },
          data: [
            { yAxis: 80, name: "低风险线", lineStyle: { color: "green" } },
            { yAxis: 60, name: "中风险线", lineStyle: { color: "orange" } },
            { yAxis: 40, name: "高风险线", lineStyle: { color: "red" } },
          ],
        },
      },
    ],
  };

  historyChart.setOption(option);
};

const handleHistoryPageChange = (page: number) => {
  historyPagination.currentPage = page;
  fetchHistoryList();
};

const handleHistorySizeChange = (size: number) => {
  historyPagination.pageSize = size;
  historyPagination.currentPage = 1;
  fetchHistoryList();
};

const viewHistoryDetail = (id: number) => {
  ElMessage.info(`查看历史记录 ${id} 的详情`);
};

// 获取整改建议
const fetchRemediationAdvice = async () => {
  if (!assetIp.value) return;

  adviceLoading.value = true;
  try {
    const { data } = await getRemediationAdvice({
      asset_ip: assetIp.value,
    });

    if (data) {
      remediationAdvice.value = data;
    }
  } catch (error: any) {
    console.error("获取整改建议失败:", error);
    ElMessage.error(error?.message || "获取整改建议失败");
  } finally {
    adviceLoading.value = false;
  }
};

// 打开整改建议对话框
const handleShowSuggestions = () => {
  showSuggestions.value = true;
  if (!remediationAdvice.value) {
    fetchRemediationAdvice();
  }
};

// 标记误报
const handleMarkFalsePositive = () => {
  if (!activeDimension.value || !currentDimensionDetail.value) {
    ElMessage.warning("请先选择一个维度");
    return;
  }

  const dimension = currentDimensionDetail.value;
  if (dimension.is_false_positive) {
    ElMessage.warning("该维度已标记为误报");
    return;
  }

  if (dimension.deduction === 0) {
    ElMessage.warning("该维度无扣分，无需标记误报");
    return;
  }

  falsePositiveForm.marked_by = localStorage.getItem("username") || "admin";
  showFalsePositiveDialog.value = true;
};

// 提交误报标记
const submitFalsePositive = async () => {
  if (!falsePositiveForm.false_positive_reason.trim()) {
    ElMessage.warning("请输入误报原因");
    return;
  }

  if (!falsePositiveForm.evidence.trim()) {
    ElMessage.warning("请提供支持证据");
    return;
  }

  try {
    loading.value = true;
    const { data } = await markFalsePositive({
      asset_ip: assetIp.value,
      dimension_code: activeDimension.value,
      false_positive_reason: falsePositiveForm.false_positive_reason,
      evidence: falsePositiveForm.evidence,
      handling_method: falsePositiveForm.handling_method,
      marked_by: falsePositiveForm.marked_by,
    });

    if (data) {
      ElMessage.success("标记成功！");
      if (data.after_mark) {
        const improvement = data.after_mark.score_improvement;
        ElMessage.info(`评分已提升 ${improvement.toFixed(2)} 分`);
      }
      showFalsePositiveDialog.value = false;
      await fetchAssetDetail();
    }
  } catch (error: any) {
    console.error("标记误报失败:", error);
    ElMessage.error(error?.message || "标记误报失败");
  } finally {
    loading.value = false;
  }
};

// 取消误报标记
const handleUnmarkFalsePositive = async () => {
  if (!activeDimension.value || !currentDimensionDetail.value) {
    return;
  }

  const dimension = currentDimensionDetail.value;
  if (!dimension.is_false_positive) {
    return;
  }

  try {
    await ElMessageBox.confirm("确定要取消误报标记吗？", "确认取消", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    loading.value = true;
    const { data } = await unmarkFalsePositive({
      asset_ip: assetIp.value,
      dimension_code: activeDimension.value,
      unmarked_by: localStorage.getItem("username") || "admin",
    });

    if (data) {
      ElMessage.success("取消误报标记成功");
      await fetchAssetDetail();
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("取消误报标记失败:", error);
      ElMessage.error(error?.message || "取消误报标记失败");
    }
  } finally {
    loading.value = false;
  }
};

// 监听历史对话框打开
watch(showHistory, (val) => {
  if (val) {
    fetchHistoryList();
  }
});

// 组件卸载时清理图表
onUnmounted(() => {
  if (historyChart) {
    historyChart.dispose();
    historyChart = null;
  }
});

// 页面加载时获取数据
onMounted(() => {
  fetchAssetDetail();
});
</script>

<style scoped lang="scss">
.risk-detail-container {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
}

.header-operation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;

  .page-title {
    font-size: 18px;
    font-weight: 600;
    color: #1d2129;
    display: flex;
    align-items: center;
  }

  .operation-buttons {
    display: flex;
    gap: 8px;
  }
}

.basic-info-card {
  margin-bottom: 20px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;

  .card-header {
    display: flex;
    align-items: center;
    font-weight: 500;
    color: #1d2129;
  }

  .basic-info-descriptions {
    margin-top: 10px;

    .monospace-text {
      font-family: monospace;
      background-color: #f5f5f5;
      padding: 2px 6px;
      border-radius: 3px;
    }
  }
}

.score-risk-container {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;

  .score-card,
  .risk-card {
    flex: 1;
    min-width: 300px;
    border-radius: 6px;
    border: 1px solid #f0f0f0;

    .card-header {
      display: flex;
      align-items: center;
      font-weight: 500;
      color: #1d2129;
    }
  }

  .score-content {
    padding: 20px 0;
    text-align: center;

    .score-value {
      font-size: 36px;
      font-weight: 700;
      color: #165dff;
      line-height: 1;

      .score-max {
        font-size: 16px;
        color: #86909c;
        font-weight: normal;
        margin-left: 4px;
      }
    }

    .score-history {
      color: #86909c;
      margin-top: 8px;
      font-size: 14px;
    }
  }

  .risk-content {
    padding: 15px 0;

    .risk-level {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
    }

    .risk-description {
      color: #4e5969;
      margin-bottom: 15px;
      line-height: 1.6;
    }

    .risk-actions {
      display: flex;
      gap: 10px;
    }
  }
}

.dimension-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;

  .card-header {
    display: flex;
    align-items: center;
    font-weight: 500;
    color: #1d2129;
  }

  .dimension-tabs {
    margin-top: 15px;

    ::v-deep .el-tabs__nav {
      margin-bottom: 15px;
    }

    ::v-deep .el-tabs__item {
      padding: 0 15px;
    }

    ::v-deep .el-tabs__item.is-active {
      color: #165dff;
      font-weight: 500;
    }

    ::v-deep .el-tabs__active-bar {
      background-color: #165dff;
    }
  }

  .dimension-content {
    padding: 10px 0;
  }

  .dimension-detail-card {
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    overflow: hidden;

    .detail-header {
      padding: 15px 20px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      align-items: center;
      gap: 10px;

      .detail-title {
        font-size: 16px;
        font-weight: 500;
        margin: 0;
      }

      .detail-score {
        display: flex;
        align-items: center;
      }
    }

    .detail-item {
      padding: 12px 20px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      align-items: center;

      .detail-label {
        width: 120px;
        color: #4e5969;
        flex-shrink: 0;
      }

      .detail-value {
        flex-grow: 1;
      }
    }

    .detail-section {
      padding: 15px 20px;
      border-bottom: 1px solid #f0f0f0;

      .section-title {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 10px;
        color: #1d2129;
      }

      .detail-descriptions {
        ::v-deep .el-descriptions__label {
          font-weight: 500;
          color: #4e5969;
        }
      }

      .calculation-descriptions {
        ::v-deep .el-descriptions__item {
          padding: 8px 12px;
        }

        ::v-deep .el-descriptions__label {
          font-weight: 500;
          color: #4e5969;
        }
      }

      .final-deduct {
        ::v-deep .el-descriptions__content {
          .deduct-value {
            font-size: 16px;
            color: #ff4d4f;
            font-weight: 500;
          }
        }
      }
    }

    .detail-actions {
      padding: 15px 20px;
      display: flex;
      gap: 10px;
      justify-content: flex-end;
    }
  }
}

.suggestion-content {
  .suggestion-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
  }

  .suggestion-list {
    padding-left: 10px;
  }

  .suggestion-item {
    display: flex;
    margin-bottom: 12px;
    line-height: 1.6;

    .suggestion-number {
      font-weight: 600;
      color: #165dff;
      margin-right: 10px;
      flex-shrink: 0;
    }
  }
}

.advice-content {
  padding: 15px 0;

  .advice-section {
    margin-top: 20px;

    h4 {
      margin-bottom: 10px;
      color: #303133;
      font-size: 14px;
      font-weight: 500;
    }

    p {
      color: #606266;
      line-height: 1.6;
      margin-bottom: 8px;
    }

    ol {
      color: #606266;
      line-height: 1.8;
    }
  }
}

.fade-in {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.risk-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 6px;
}
</style>
